<template>
  <view class="cart-box" v-if="cart.length !== 0">
    <!-- 收货地址组件 -->
    <my-address></my-address>
    <!-- 购物车标题 -->
    <view class="shop_cart">
      <uni-icons type="shop" size="18"></uni-icons>
      <text>购物车</text>
    </view>
    <!-- 购物车列表 -->
    <uni-swipe-action>
      <block v-for="(item, i) in cart" :key="i">
        <uni-swipe-action-item :right-options="options" @click="deleteItem(item)">
          <my-goods :good="item" @changeHandler="changeHandler"></my-goods>
        </uni-swipe-action-item>
      </block>
    </uni-swipe-action>
    <!-- 底部盒子 -->
    <view class="btm_box">
      <!-- 全选 -->
      <label class="btm_radio">
        <radio color="red" @click="SelectAll" :checked="allselect" />
        <text>全选</text>
      </label>
      <!-- 合计 -->
      <view>
        合计:
        <text class="amount">￥{{ totals }}</text>
      </view>
      <!-- 结算 -->
      <view class="settlement" @click="settlement">
        <bottom class="s_text">结算({{ count }})</bottom>
      </view>
    </view>
  </view>
  <view class="blankPage" v-else>空空如也</view>
</template>

<script>
import badgeMix from '@/mixins/tabbar_badge.js';
import { mapState, mapGetters } from 'vuex';
export default {
  mixins: [badgeMix],
  data() {
    return {
      options: [
        {
          text: '删除',
          style: {
            backgroundColor: '#dd524d'
          }
        }
      ],
      seconds: 3
    };
  },
  computed: {
    ...mapState('cart', ['cart']),
    ...mapGetters('user', ['addstr']),
    ...mapGetters('cart', ['allselect', 'selected']),
    ...mapState('user', ['token', 'user']),
    totals() {
      return this.selected
        .reduce((total, itme) => (total += itme.goods_price * itme.goods_count), 0)
        .toFixed(2);
    },
    count() {
      let c = 0;
      this.selected.forEach(x => {
        c += x.goods_count;
      });
      return c;
    }
  },
  methods: {
    SelectAll() {
      this.$store.commit('cart/selectAll');
    },
    deleteItem(e) {
      const good = e.goods_id;
      this.$store.commit('cart/deleteItem', good);
    },
    settlement() {
      if (!this.token) return this.delayNavigate();
      if (this.count === 0) return uni.$showMsg('请选择要结算的商品');
      if (!this.addstr) return uni.$showMsg('请选择收货地址');
      this.payOrder();
    },
    async payOrder() {
      const orderInfo = {
        order_price: 0.01,
        order_addr: this.user,
        goods: this.selected.map(x => ({
          goods_id: x.goods_id,
          goods_number: x.goods_count,
          goods_price: x.goods_price
        }))
      };
      const { data: res } = await uni.$http.post('/api/public/v1/my/orders/create', orderInfo);
      if (res.meta.status !== 200) return uni.$showMsg('创建订单失败');
      const orderNumber = res.message.order_number;
      const orderId = res.message.user_id;
      const res2 = await uni.$http.post('/api/public/v1/my/orders/req_unifiedorder', {
        order_number: orderNumber
      });
      // 获取订单编号
      const payInfo = {
        nonceStr: 'IetkN22VgkNYQr8T',
        package: 'prepay_id-wx01124228305228b1aa856d4d868d4b0000',
        paySign: ' 8DA78D5EA9CC52C520A686CD00B923F5',
        signType: 'MD5',
        timeStamp: '1598935352'
      };
      this.createOrder(payInfo);
    },
    // 发起支付
    async createOrder(payInfo) {
      const [err, succ] = await uni.requestPayment(payInfo).catch(err => err);
      if (err) return uni.$showMsg('订单支付失败');
      // 支付成功后查询订单支付结果
      const { data: res3 } = await uni.$http.post('/api/public/v1/my/orders/chkOrder', {
        order_number: orderNumber
      });
      if (res3.meta.status !== 200) return uni.$showMsg('订单未支付！');
      uni.showToast({
        title: '支付完成！',
        icon: 'success'
      });
    },
    // 倒计时到my页面
    delayNavigate() {
      this.seconds = 3;
      this.showTips(this.seconds);
      const timer = setInterval(() => {
        this.seconds--;
        this.showTips(this.seconds);
        if (this.seconds <= 0) {
          clearInterval(timer);
          uni.switchTab({
            url: '/pages/my/my',
            success: () => {
              this.$store.commit('user/updataRediectInfo', {
                openType: 'switchTab',
                from: '/pages/cart/cart'
              });
            }
          });
        }
      }, 1000);
    },
    // 展示提示消息
    showTips(n) {
      uni.showToast({
        title: `请登陆后再结算!\n${n}秒后自动跳转到登录页`,
        icon: 'none',
        mask: true,
        duration: 1100
      });
    }
  }
};
</script>

<style lang="scss">
.cart-box {
  padding-bottom: 50px;
}
.shop_cart {
  height: 40px;
  display: flex;
  margin-left: 5px;
  align-items: center;
  border-bottom: 1px solid #efefef;
  text {
    margin-left: 5px;
    font-size: 14px;
  }
}
.shop_list {
  height: 100px;
  display: flex;
  align-items: center;
  margin: 5px 0px;
  .radio {
    radio {
      transform: scale(0.7);
    }
  }
  .shop_img_box {
    height: 100px;
    .shop_img {
      width: 100%;
    }
  }
  .shop_item {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-left: 10px;
    height: 100%;
    .shop_name {
      font-size: 14px;
    }
    .shop_btm_box {
      .shop_price {
        color: #c00000;
      }
    }
  }
}
.btm_box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: fixed;
  bottom: 0;
  left: 0;
  height: 50px;
  width: 100%;
  background-color: #efefef;
  .settlement {
    width: 100px;
    height: 100%;
    background-color: #c00000;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .btm_radio {
    padding-left: 5px;
  }
  .amount {
    color: #c00000;
    font-weight: 700;
  }
}
.blankPage {
  height: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
